
require 'fastdb/record'

module Ph

class Table

	attr_reader :name, :record, :database

	def initialize(name, db, &block)
		@name 	= name
#		@record = Class.new(Ph::Record)
		@record = Hash.new
		@links  = Array.new
		@database = db
		instance_eval(&block)
	end

	#
	# Table Creation
	#
	
	def field(options)
		options.merge!({:caption => options[:name].to_s.capitalize}) unless options.has_key?(:caption)
		@record[options[:name]] = options # Mysql::Field.new()
	end
	
	def id(symbol=:id)
		self.field({:name => symbol, :type => :id, :size => 10, :auto => true })
	end

	def invalid_link(from, msg)
		raise "Invalid Link '#{@name}.#{from}': #{msg}"
	end

	def link(from, to, link)
		# Handle link to the table itself
		e = (link == @name) ? self : @database.elements[link]
		invalid_link(from, "#{@database.name}.#{link} does not exist.") unless e
		invalid_link(from, "#{@database.name}.#{link}.#{to} does not exist.") unless l = e.record[to]

		x = self.field({:name => from.to_s, :type => :int, :link => l, :size => 10 })
		@links << x		
	end

	def string(size, *name)
		name.each do |s|
			self.field({:name => s.to_s, :type => :string, :size => size })
		end
	end

	def text(*name)
		name.each do |s|
			self.field({:name => s.to_s, :type => :text })
		end
	end

	def time(*name)
		name.each do |s|
			self.field({:name => s.to_s, :type => :date, :size => 13 })
		end
	end

	def int(size, *name)
		name.each do |s|
			self.field({:name => s.to_s, :type => :int, :size => size })
		end
	end

	def currency(*name)
		name.each do |s|
			self.field({:name => s, :type => :double, :size => 10, :decimal => 2})
		end
	end

end

end 
